package wangjg.security.util.matcher;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 用正则表达式实现的通配符匹配
 * 支持*,?
 * @author wangjg
 *
 */
public class RegWildcard {
	private String[] parameters;
	
    public boolean matches(String pattern, String input) {
    	String regex = toRegex(pattern);
        Pattern p = Pattern.compile(regex);
        Matcher m = p.matcher(input);
        boolean b = m.matches();
        if(b){
	        this.parameters=new String[m.groupCount()];
	        for(int i=0;i<m.groupCount();i++){
	        	parameters[i] = m.group(i+1);
	        }
        }
        return b;
    }
	
	static String toRegex(String wildCard){
		String s=wildCard;
		StringBuffer output = new StringBuffer();
		int len = s.length ();
        for(int i=0; i<len; ++i){
        	char c = s.charAt(i);
        	switch(c){
            case '*':
                output.append ("(.*)");
            	break;
            case '?':
            	output.append (".");
            	break;
        	case '$':
            case '(':
            case ')':
        	case '+':
            case '.':
            case '[':
            case '\\':
            case '^':
            case '{':
            case '|':
              output.append ('\\');
              output.append (c);
              break;
            default:
              output.append (c);
              break;
        	}
        }
		return output.toString();
	}
	
    
    public static void main (String[] args) throws Exception {
    	String s="s*s[a-z]+[0-9]{1}\\?";
    	System.out.println("  "+s);
    	System.out.println("r:"+toRegex(s));

    	System.out.println(Pattern.matches("s(.*)s\\[a-z]\\+\\[0-9]\\{1}\\\\.", "s*s[a-z]+[0-9]{1}\\?"));
    	
    	
    	RegWildcard w=new RegWildcard();
    	boolean b=w.matches("*a*b*c*d*", "a123b456c7d");
    	System.out.println("b="+b);
    	for(int i=0;i<w.parameters.length;i++){
    		System.out.println(i+"="+w.parameters[i]);
    	}
    	
    }
}
